package com.tockm.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tockm.server.config.security.JwtTokenUtil;
import com.tockm.server.mapper.AdminMapper;
import com.tockm.server.pojo.Admin;
import com.tockm.server.pojo.RespBean;
import com.tockm.server.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author tockm
 * @since 2021-12-16
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private PasswordEncoder passwordEncoder; //密码加密

    @Value("${jwt.tokenHead}")  //从yml文件中拿值
    private String tokenHead;

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public RespBean login(String username, String password, HttpServletRequest request) {
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        //
//        System.out.println("=========userDetails"+userDetails);
//        System.out.println("=========password"+password);
        //
        if (userDetails==null||passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("登录过期");
        }
        if (!userDetails.isEnabled()){
            return RespBean.error("账号禁用，请联系管理员！");
        }
        //更新token
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);


        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return RespBean.success("登录成功",tokenMap);
    }

    @Override
    public Admin getAdminByUserName(String username) {
        //return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username).eq("enabled",true));
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username));
    }
}
